<template>
  <div class="todoapp">
    <h1>Todo List</h1>
    <input
      class="new-todo"
      placeholder="你接下来要做什么"
      v-model="newTodo"
      v-autofocus
      @keyup.enter="addTodo"
    />
    <ul class="todo-list">
      <li
        v-for="todo in todos"
        :key="todo.id"
        class="todo"
        :class="{ completed: todo.completed, editing: todo.id === editedTodo.id }"
      >
        <div class="view">
          <!-- 选择某条备忘 -->
          <input class="toggle" type="checkbox" v-model="todo.completed" />
          <!-- 双击编辑备注 -->
          <label @dblclick="editTodo(todo)">{{ todo.title }}</label>
          <!-- 删除某天备注 -->
          <button class="destroy" @click="removeTodo(todo)"></button>
        </div>
        <!-- 修改备忘的数据，失焦或 Enter 键可更新数据，Esc 键取消更新 -->
        <input
          type="text"
          class="edit"
          v-model="editedTodo.title"
          @blur="doneEdit(editedTodo)"
          @keyup.enter="doneEdit(editedTodo)"
          @keyup.esc="cancelEdit"
        />
      </li>
    </ul>
    <footer class="footer" v-show="todos.length">
      <span class="todo-count">
        <!-- remaining 计算剩余的未完成数量，plurlize 用来过滤单位是否复数 -->
        <strong> {{ remaining }}</strong> {{ remaining | pluralize }} left
      </span>
      <button class="clear-completed" v-show="todos.length > remaining">clear completed</button>
    </footer>
  </div>
</template>

<script>
export default {
  name: 'Home',
  computed: {
    remaining () {
      return this.todos.filter(todo => !todo.completed).length
    }
  },
  data () {
    return {
      todos: [],
      newTodo: [],
      editedTodo: {}
    }
  },
  filters: {
    // 计算单位
    pluralize (num) {
      return num > 1 ? 'items' : 'item'
    }
  },
  methods: {
    // 取消修改备注
    cancelEdit () {
      this.editedTodo = {}
    },
    // 确认修改备忘
    doneEdit (editedTodo) {
      this.todos = this.todos.map(
        todo => (todo.id === editedTodo.id ? { ...editedTodo } : { ...todo })
      )
      this.editedTodo = {}
    },
    // 删除备注
    removeTodo (todo) {
      const index = this.todos.findIndex(item => item.id === todo.id)
      this.todos.splice(index, 1)
    },
    // 编辑备忘
    editTodo (todo) {
      this.editedTodo = { ...todo }
    },
    // 添加备忘
    addTodo () {
      if (!this.newTodo) return
      const time = new Date().getTime()
      this.todos.unshift({
        id: time,
        title: this.newTodo,
        completed: false
      })
      this.newTodo = ''
    }
  }
}
</script>

<style lang="less" scoped>
@import url("https://unpkg.com/todomvc-app-css@2.1.0/index.css");
</style>
